package Network

import (
	"SQL/FSDB"
	"database/sql"

	_ "github.com/lib/pq"
)

type FriendSessionRow struct {
	TalkerID      string `json:"TalkerID"`
	TalkerName    string `json:"TalkerName"`
	TalkerIconURL string `json:"TalkerIconURL"`
	SenderID      string `json:"SenderID"`
	MsgID         string `json:"MsgID"`
	MsgType       string `json:"MsgType"`
	Msg           string `json:"Msg"`
	CreateTime    string `json:"CreateTime"`
	UnreadNum     int    `json:"UnreadNum"`
}

func friendSessionInContext(tx *sql.Tx, userID string) (errCode int, errMsg string, list interface{}) {

	getFriendSessionSQL := `SELECT * FROM getFriendSession($1);`
	gfsStmt, gfsRows, err := FSDB.QueryTx(tx, getFriendSessionSQL, userID)
	if err != nil {
		return errEndTx, "getFriendSessionSQL tx.QueryTx 执行错误：" + err.Error(), nil
	}
	defer gfsStmt.Close()
	defer gfsRows.Close()

	sessionRows := make([]FriendSessionRow, 0)

	var (
		talkerID      string
		talkerName    string
		talkerIconURL string
		senderID      string
		msgID         string
		msgType       string
		msg           string
		createTime    string
		unreadNum     int
	)

	for gfsRows.Next() {
		err = gfsRows.Scan(&talkerID, &talkerName, &talkerIconURL, &senderID, &msgID, &msgType, &msg, &createTime, &unreadNum)
		if err != nil {
			return errEndTx, "gfsRows.Scan 执行错误：" + err.Error(), nil
		}
		sessionRow := FriendSessionRow{
			TalkerID:      talkerID,
			TalkerName:    talkerName,
			TalkerIconURL: talkerIconURL,
			SenderID:      senderID,
			MsgID:         msgID,
			MsgType:       msgType,
			Msg:           msg,
			CreateTime:    createTime,
			UnreadNum:     unreadNum,
		}
		sessionRows = append(sessionRows, sessionRow)
	}
	return Success, "成功获取 " + userID + " 的会话列表！", sessionRows
}
